package com.lmy.androidcustomview.view

import android.content.Context
import android.graphics.*
import android.os.Build
import android.util.AttributeSet
import android.view.View
import androidx.annotation.RequiresApi
import com.lmy.androidcustomview.toPx
import kotlin.math.cos
import kotlin.math.sin

/**
 * @author lmy
 * @功能: 饼图自定义View  和偏移量
 * @Creat 2/8/21 4:10 PM
 * @Compony 465008238@qq.com
 */
class PieChartView(context: Context?, attrs: AttributeSet) : View(context, attrs) {
    private val paint = Paint(Paint.ANTI_ALIAS_FLAG)
    val RADIUS = 150f//半径
    private val ANGLES = floatArrayOf(60f, 90f, 150f, 60f)
    val OFFSET_LENGTH=20f.toPx
    private val COLORS = listOf(
        Color.parseColor("#49aef8"),
        Color.parseColor("#9279a6"),
        Color.parseColor("#6200ee"),
        Color.parseColor("#bc822f")
    )

    @RequiresApi(Build.VERSION_CODES.LOLLIPOP)
    override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {

    }

    @RequiresApi(Build.VERSION_CODES.LOLLIPOP)
    override fun onDraw(canvas: Canvas) {
        var startAngle = 0f
        for ((index, angle) in ANGLES.withIndex()) {
            paint.color = COLORS[index]
            if (index==1){
                //这里计算的时候不要忘记加上开始的偏移的角度
                canvas.save()
                canvas.translate((OFFSET_LENGTH *cos(Math.toRadians(startAngle+(angle/2f).toDouble()))).toFloat(), (OFFSET_LENGTH*sin(Math.toRadians(
                    (startAngle+angle/2f).toDouble()
                ))).toFloat())
            }
            canvas.drawArc(
                width / 2f - RADIUS.toPx,
                height / 2f - RADIUS.toPx,
                width / 2f + RADIUS.toPx,
                height / 2f + RADIUS.toPx,
                startAngle,
                angle,
                true,
                paint
            )
            startAngle += angle
            if (index==1){
                //恢复偏移
                canvas.restore()
            }
        }
    }
}